//
//  LocationManager.m
//  WeatherGuide
//
//  Created by lanou3g on 15/12/18.
//  Copyright © 2015年 李明. All rights reserved.
//

#import "LocationManager.h"

#import "GetDataFromURLTool.h"

@interface LocationManager ()<CLLocationManagerDelegate>

@property (nonatomic,strong) CLLocationManager *locationManager;
@end


static LocationManager *manager = nil;
@implementation LocationManager

+ (instancetype)sharedLocationMagager
{
    return [[self alloc] init];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (manager == nil) {
            manager = [super allocWithZone:zone];
        }
    });
    return manager;
}

#pragma mark 开始定位
- (void)startLocation
{
    
    NSLog(@"111");
    if (self.locationManager == nil) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        NSLog(@"ssssss");
        [self.locationManager requestWhenInUseAuthorization];
    }
    
    CLLocationDistance distance = 10.0f;
    self.locationManager.distanceFilter = distance;
    
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    if ([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
        
        [self.locationManager startUpdatingLocation];
        
        NSLog(@"11");
    }

}

#pragma mark 更新了位置信息的代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
//    NSLog(@"=========");
   
    CLLocation *location = locations.firstObject;
//    NSLog(@"aaaaaaaa -    ");
    
//    NSLog(@"2222222%@",location.description);
    if (self.upDataBlock) {
        
        CLLocationCoordinate2D coordinate = location.coordinate;
        coordinate = [self getMarsCoorWithEarthCoor:coordinate];
        self.upDataBlock(coordinate,self.locationManager);
        [self.locationManager stopUpdatingLocation];
        self.locationManager = nil;
        
//        self.upDataBlock
    }
    
    
}


#pragma mark 逆地理编码--根据经纬度获取地址
- (void)getAddressWithCoordianate:(CLLocationCoordinate2D)coordinate
                  withFinishBlock:(upGecgraphyCodingBlock)finishBlock
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    CLLocation *location = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            CLPlacemark *placemark = placemarks.firstObject;
            finishBlock(placemark.locality);
        });
    }];
}

#pragma mark 更新当前位置天气

+ (void)updataWeatherForCurrentLocationupdata:(updataBLOCK)finishBlock
{
    [[LocationManager sharedLocationMagager] startLocation];
    
    
    [LocationManager sharedLocationMagager].upDataBlock = ^(CLLocationCoordinate2D coordinate2D ,CLLocationManager *manager){
        
        [[LocationManager sharedLocationMagager] getAddressWithCoordianate:coordinate2D withFinishBlock:^(NSString *name) {
            
            name = [name substringToIndex:name.length - 1];

//            NSLog(@"%@",name);
            [GetDataFromURLTool getDataFromURLStr:name backBlock:^(id object){
                
                finishBlock();
            }];
            
        }];
    };
    
}


#pragma mark -火星坐标

const double pi = 3.14159265358979324;
const double a = 6378245.0;
const double ee = 0.00669342162296594323;


//将CLLocation定位的coordinate传进来，就可以计算出用于在高德地图中使用的火星坐标了
-(CLLocationCoordinate2D)getMarsCoorWithEarthCoor:(CLLocationCoordinate2D)earthCoor
{
    CLLocationCoordinate2D marsCoor;
    if (outOfChina(earthCoor.latitude, earthCoor.longitude)) {
        marsCoor = earthCoor;
        return marsCoor;
    }
    double dLat = transformLat(earthCoor.longitude-105.0, earthCoor.latitude-35.0);
    double dLon = transformLon(earthCoor.longitude-105.0, earthCoor.latitude-35.0);
    double radLat = earthCoor.latitude/180.0*pi;
    double magic = sin(radLat);
    magic = 1-ee*magic*magic;
    double sqrtMagic = sqrt(magic);
    dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
    dLon = (dLon * 180.0) / (a / sqrtMagic * cos(radLat) * pi);
    marsCoor = CLLocationCoordinate2DMake(earthCoor.latitude+dLat, earthCoor.longitude+dLon);
    return marsCoor;
}

static bool outOfChina(double lat, double lon)
{
    if (lon < 72.004 || lon > 137.8347)
        return true;
    if (lat < 0.8293 || lat > 55.8271)
        return true;
    return false;
}

static double transformLat(double x, double y)
{
    double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(abs(x));
    ret += (20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 / 3.0;
    ret += (20.0 * sin(y * pi) + 40.0 * sin(y / 3.0 * pi)) * 2.0 / 3.0;
    ret += (160.0 * sin(y / 12.0 * pi) + 320 * sin(y * pi / 30.0)) * 2.0 / 3.0;
    return ret;
}

static double transformLon(double x, double y)
{
    double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(abs(x));
    ret += (20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 / 3.0;
    ret += (20.0 * sin(x * pi) + 40.0 * sin(x / 3.0 * pi)) * 2.0 / 3.0;
    ret += (150.0 * sin(x / 12.0 * pi) + 300.0 * sin(x / 30.0 * pi)) * 2.0 / 3.0;
    return ret;
}
-(BOOL)ismainStringContainSubString:(NSString *)mainString  subString:(NSString *)subString
{
    
    NSRange range=[mainString rangeOfString:subString];
    if(range.location!=NSNotFound){
        return true;
    }else{
        return false;
    }
}


@end
